<?php

/*
	Class: App_Controller_Action_Abstract

	About: Author
		J William McCarthy

	About: License
		<http://communit.as/docs/license>

	About: See Also
		Zend_Controller_Action
*/
abstract class App_Controller_Action_Abstract extends Zend_Controller_Action {

	/* Group: Instance Variables */

	/*
		Variable: $_logger
	*/
	protected $_logger;

	/* Group: Instance Methods */

	/*
		Function: init
			Initializes the current instance.

		View Variables:
			host_id - TBD
			baseUrl - TBD
			site_url - The base URL of the website. Pulled from the registry.
			site_name - The value of site_name from the registry passed out unaltered.
			In case of no registry entry, defaults to "Friend Factory".
			admin_role - The name of the admin role. Pulled from the registry.
			guest_role - The name of the guest role. Pulled from the registry.
			mca - A concatenation of the names of the model, controller, and action.
			Useful as a body class selector when you want different models,
			controllers, and/or actions to be styled differently.
			controller_name - The name of the current controller.
			module_name - The name of the current module.
			action_name - The name of the current action.
			isLoggedIn - Indicates whether the current user is logged in. (boolean)
			loggedInUsername - The username of the current user if they are logged in, or null otherwise.
			loggedInFullName - The full name of the current user if they are logged in, or null otherwise.
			loggedInRoleId - The role ID of the current user if they are logged in, or null otherwise.
			isAdmin - Indicates whether the current user is a member of the administrator role. (boolean)
			last_login - TBD
			format_date - A format string for date. Pulled from the registry.
			format_datetime - A format string for date with time. Pulled from the registry.
			format_datetime_small - A format string for short date and time. Pulled from the registry.
			current_year - The current year as a 4 digit integer.
			theme_url - TBD
			theme_global - TBD
			has_onload - TBD
			loadEditor - TBD
			title_prefix - TBD
			view_states - An array of key value pairs (stored in the session) representing the state of certain pages.
				For instance, the last time you viewed the list of users, you were on page 3.

		Plugin Hooks:
			- *controller_init* (filter) - Allows you to perform additional actions just before the init method terminates.
				param username - The username of the current user if they are logged in, or null otherwise.
			- *controller_nav* (filter) - Allows you to modify the navigation array before it is assigned to the view.
				param nav_items - The array of links returned by the Navigation model class.
				param request - The HTTP Request object.
	*/
    function init() {

    	$params = array('username' => null);

		$this->_uri = $_SERVER['REQUEST_URI'];
		$this->_host_id = Zend_Registry::get('host_id');
		$this->view->host_id = $this->_host_id; 
    	$this->_logger = Zend_registry::get('logger');
	    $this->view->baseUrl = $this->_request->getBaseUrl();
	    $this->view->site_url = App_Registry::get('site_url', 'http://' . $_SERVER['SERVER_NAME']);
	    $this->view->site_name = App_Registry::get('site_name', 'Friend Factory');
	    $this->registry = Zend_Registry::getInstance();
	    $this->view->admin_role = Zend_Registry::get('admin_role');
        $this->view->guest_role = Zend_Registry::get('guest_role');
	    $this->session = new Zend_Session_Namespace('Default');

	    $this->_mca = $this->_request->getModuleName() . "_" . $this->_request->getControllerName() . "_" . $this->_request->getActionName();
	    $this->view->mca = str_replace("_", "-", $this->_mca);
	    $this->view->controller_name = $this->_request->getControllerName();
	    $this->view->module_name = $this->_request->getModuleName();
	    $this->view->action_name = $this->_request->getActionName();
	    $this->_auth = Zend_Auth::getInstance();
    	if ($this->_auth->hasIdentity()) {
        	$this->_identity = $this->_auth->getIdentity();
        	$this->view->isLoggedIn = true;
    		$params['username'] = $this->_identity->username;
        	$this->view->loggedInUsername = $this->_identity->username;
        	$this->view->loggedInFullName = $this->_identity->full_name;
        	$this->view->loggedInRoleId = $this->_identity->role_id;
        	$roles = new Roles();
        	$role = $roles->fetchRow('id = ' . $this->_identity->role_id);
        	if ($this->_identity->role_id == $this->view->admin_role) {
        		$this->view->isAdmin = true;
        		$this->_identity->isAdmin = true;
        	}
        } else {
        	$this->_identity = null;
        	$this->view->isLoggedIn = false;
        }
        $appNamespace = new Zend_Session_Namespace('App_Temp');
        $this->view->last_login = $appNamespace->last_login;
        $this->view->format_date = App_Registry::get('format_date', "%A, %B %e, %Y");
        $this->view->format_datetime = App_Registry::get('format_datetime', "%A, %B %e, %Y at %l:%M:%S%p");
        $this->view->format_datetime_small = App_Registry::get('format_datetime_small', "%e %b %Y, %l:%M%p");
        $this->view->current_year = date("Y");
        
        $this->view->theme_url = Zend_Registry::get('theme_url');
        $this->view->default_url = Zend_Registry::get('default_url');
        $this->view->theme_global = Zend_Registry::get('theme_global_path');
        
        $this->view->has_onload = false;
        $this->view->loadEditor = false;
        $this->view->title_prefix = App_Registry::get('title_prefix', "Friend Factory");
        $this->_app_plugin = new App_Plugin;

        $frontendOptions = array(
		   'lifetime' => App_Registry::get('default_index_cache_lifetime', 300), // cache lifetime of 2 hours
		   'automatic_serialization' => true
		);

		$backendOptions = array(
		    'cache_dir' => Zend_Registry::get('basepath') . '/tmp/cache' // Directory where to put the cache files
		);

		// getting a Zend_Cache_Core object
		$this->cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);

		// get navigation items from database

		// check for role of identity, if we don't have one, use guest.
		// TODO - move this to the place where role is determined, there should only be one place
		if($this->_auth->hasIdentity()){
			$nav_role_id = $this->_identity->role_id; 
		} else {
			$nav_role_id = Zend_Registry::get('guest_role');
		}
		$nav_table = new Navigation($nav_role_id);
		$nav_items_temp = $nav_table->getNavTree($nav_role_id);

		$navparams = array('nav_items' => $nav_items_temp, 'request' => $this->_request);
		$navparams = $this->_app_plugin->doFilter('controller_nav', $navparams); // FILTER HOOK
		$this->view->nav_items = $navparams['nav_items'];

		// set up translator
		//$this->translate

		// TODO - Rich fix this
		// // VIEW STATES
		// if (!$this->session->view_states) {
		// 	$this->session->view_states = array();
		// }
		// // TODO - allow use of regular expressions such as /auth/*
		// $default_filter = '/auth/login|/auth/logout|/auth/missing|/user/register|/user/postregister|/user/edit|/default/user/postregister';
		// $last_visited_pages_filter = explode('|', App_Registry::get('last_visited_pages_filter', $default_filter));
		// if (!in_array($this->_uri, $last_visited_pages_filter)) {
		// 	$this->session->view_states['last_visited'] = $this->_uri;
		// }
		// $this->view->view_states = $this->session->view_states;

		// CONTROLLER INIT HOOK
	    $additional = $this->_app_plugin->doFilter('controller_init', $params); // FILTER HOOK
	    foreach ($additional as $key => $value) {
	    	$this->view->$key = $value;
	    }
	}

	// TODO - MOVE ALL PAGING METHODS TO A SEPARATE LIBRARY

	/* Group: Private or Protected Methods */

	/*
		Function: makePager
			Adds paging information to a view. This works independently of any collection.
			You basically describe the collection to this method and you get back some view variables.

		Arguments:
			$page - The index of the page to display. (0-based)
			$per_page - The number of items to display per page.
			$total - The total number of items in the entire collection.
			$url - The URL of the page on which the pager is being displayed.
			$params (optional) - An open-ended customizable array of key-value-paired parameters.
				Pairs passed in will be added to the $url argument as parameters.
				Default is null.

		View Variables:
			pager_url - The $url argument with optional $params added to it.
			page_info - Pager status. Information about the page you are on (e.g.: 11 to 20 of 87)
			next - The index of the page after the current page. (0-based)
			last - The index of the last page in the entire collection. (0-based)
			prev - The index of the page before the current page. (0-based)
			first - The index of the first page in the entire collection. (0-based)
			total - The total number of items being paged. This is the $total argument passed out unaltered.
			page - The index of the current page. (0-based)
			display_page - The index of the current page. (1-based)
			total_pages - The total number of pages in the entire collection.
			pages - An array of integers, one for each page in the entire collection. (1-based)
	*/
	protected function makePager($page, $per_page, $total, $url, $params = null) {

	  	foreach ($params as $key => $val) {
	  		if (!is_null($val)) {
	  			$url .= "/" . $key . "/" . $val;
	  		}
	  	}
	  	$this->view->pager_url = $url;
	  	$total_pages = ceil($total / $per_page);
		$start = ($per_page * $page);
		$end = $start + count($total);
		$start++;
		$this->view->page_info = "$start to $end of $total";

		if ($page < $total_pages - 1) {
			$this->view->next = $page + 1;
			$this->view->last = $total_pages - 1;
		}

		if ($page > 0) {
			$this->view->prev = $page - 1;
			$this->view->first = 0;
		}

		$this->view->total = $total;
		$this->view->page = $page;
		$this->view->display_page = $page + 1;
		$this->view->total_pages = $total_pages;
		$pages = array();
		for ($x = 0; $x < $total_pages; $x++ ) {
			$pages[] = $x;
		}
		$this->view->pages = $pages;
	}

}
